const {
  GiftShopModel
} = require('../../../utils/giftshop-model.js')
const giftShopModel = new GiftShopModel()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginShow: false,
    modalShow: false,
    number: 1,
    goodsInfo: {
      channelGoodsStatus: 1
    },
    details: '',
    shopId: '',
    skuId: '',
    cartNum: 0,
    currentIndex: 1,
    isJoinCart: false,
    exchangeType: 2,
    payTypes: [],
    goodsName:'',
  },

  changeType(e) {
    wx.reportAnalytics('goodsdetail_exchangetype');
    const {
      value
    } = e.currentTarget.dataset
    this.setData({
      exchangeType: value
    })
  },
  ensure() {
    const merchantId = wx.getStorageSync('merchantId')
    if (this.data.isJoinCart) {
      wx.reportAnalytics('goodsdetail_addcart');
      giftShopModel.cartAdd({
        merchantId,
        skuId: this.data.skuId,
        shopId: this.data.shopId,
        quantity: this.data.number,
        selectedPriceType: this.data.exchangeType
      }).then(data => {
        this.getCartNum()
        this.setData({
          modalShow: false
        })
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none'
        })
      })
    } else {
      wx.reportAnalytics('goodsdetail_pay');
      const data = [{
        skuId: this.data.skuId,
        quantity: this.data.number,
        selectedPriceType: this.data.exchangeType
      }]
      console.log(JSON.stringify(data))
      wx.navigateTo({
        url: `/pages/giftShop/fillOrder/index?currency=${JSON.stringify(data)}&paymentType=2`
      })
    }
  },
  joinShoppingCart() {
    if (app.globalData.isLogin) {
      if (this.data.goodsInfo.channelGoodsStatus === 1 && !this.data.goodsInfo.soldOut) {
        this.setData({
          modalShow: true,
          isJoinCart: true
        })
      }
    } else {
      this.setData({
        loginShow: true
      })
    }
  },
  buyNow() {
    if (app.globalData.isLogin) {
      if (this.data.goodsInfo.channelGoodsStatus === 1 && !this.data.goodsInfo.soldOut) {
        this.setData({
          modalShow: true,
          isJoinCart: false
        })
      }
    } else {
      this.setData({
        loginShow: true
      })
    }
  },
  closeModal() {
    wx.reportAnalytics('goodsdetail_close');
    this.setData({
      modalShow: false
    })
  },
  showPhoto() {
    const urls = this.data.goodsInfo.multimediaList.map(item => item.multUrl)
    wx.previewImage({
      urls,
      current: urls[this.data.currentIndex - 1]
    })
  },
  decrease() {
    wx.reportAnalytics('goodsdetail_quantity_decrease');
    const number = +this.data.number
    if (number > 1) {
      this.setData({
        number: number - 1 + ''
      })
    }
  },
  increase() {
    wx.reportAnalytics('goodsdetail_quantity_increase');
    const number = +this.data.number
    if (number < 99) {
      this.setData({
        number: number + 1 + ''
      })
    }
  },
  inputNum(event) {
    if (event.detail.value === '' || event.detail.value === '0') {
      wx.showToast({
        title: '请填写正确数量',
        icon: 'none'
      })
      this.setData({
        number: '1'
      })
    } else {
      this.setData({
        number: event.detail.value
      })
    }
  },
  currentBannerChange(e) {
    this.setData({
      currentIndex: e.detail.current + 1
    })
  },
  goShoppingCart() {
    wx.reportAnalytics('goodsdetail_cart');
    wx.navigateTo({
      url: '/pages/giftShop/shoppingCart/index',
    })
  },

  getDetail() {
    const merchantId = wx.getStorageSync('merchantId')
    giftShopModel.getShopDetail({
      merchantId,
      skuId: this.data.skuId,
      shopId: this.data.shopId
    }).then(data => {
      data._integerPrice = ((data.goodsPrices || []).filter(item => item.priceType === 1)[0] || {}).amount
      data._beanPrice = ((data.goodsPrices || []).filter(item => item.priceType === 2)[0] || {}).amount
      if (data._integerPrice !== undefined && data._beanPrice !== undefined) {
        this.setData({
          payTypes: [{
            label: '飞豆',
            value: 2
          }, {
            label: '积分',
            value: 1
          }],
          exchangeType: 2
        })
      } else if (data._integerPrice !== undefined) {
        this.setData({
          payTypes: [{
            label: '积分',
            value: 1
          }],
          exchangeType: 1
        })
      } else if (data._beanPrice !== undefined) {
        this.setData({
          payTypes: [{
            label: '飞豆',
            value: 2
          }],
          exchangeType: 2
        })
      }
      let goodsHtml = JSON.parse(data.goodsHtml || '{}')
      // let reshtml = data.goodsHtml || ''
      // const html = reshtml.replace(/&nbsp;/g, '<span style="width: 4px; display: inline-block"></span>')
      // const { screenWidth } = wx.getSystemInfoSync()
      // const htmlWidth = 750
      // const formatHtml = `<div style="zoom: ${screenWidth/htmlWidth}">${html}</div>`
      wx.request({
        url: `https://${goodsHtml.v1}`,
        success: (res) => {
          const {
            screenWidth
          } = wx.getSystemInfoSync()
          const htmlWidth = 750
          const formatHtml = `<div style="zoom: ${screenWidth/htmlWidth}">${res.data}</div>`
          this.setData({
            details: formatHtml
          })
        }
      })
      this.setData({
        goodsInfo: data,
        goodsName: data ? (data.title || data.skuName) : ''
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },

  loginSucc() {
    this.getCartNum()
  },

  getCartNum() {
    const merchantId = wx.getStorageSync('merchantId')
    giftShopModel.cartNum({
      merchantId,
      shopId: this.data.shopId
    }).then(data => {
      this.setData({
        cartNum: data.totalCount
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  /** 
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      shopId: options.shopId,
      skuId: options.skuId,
      channelGoodsId: options.channelGoodsId
    })
  },
  onShow() {
    this.getDetail()
    if (app.globalData.isLogin) {
      this.getCartNum()
    }
  }
})